import { useRefValue } from '@gnlab/utils/env-react'
import { Popconfirm, Button, Checkbox } from 'antd'
import { OrderedSet } from 'immutable'
import { EditModal, Actionable } from '@/desktop/components'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import type { QywxInfo } from '@/services/qywxs'

export function BatchAction(props: {
  qywxs: QywxInfo[]
  initialChoosed: string | null
  startTransfer: (qywxs: QywxInfo[]) => void
  logout: (wxids: string[]) => void
  onCancel: () => void
}) {
  const { qywxs, initialChoosed, startTransfer, logout, onCancel } = props

  return <EditModal
    open={initialChoosed !== null}
    title="批量操作"
    css={s.modal}
    onCancel={onCancel}
  >
    {initialChoosed !== null ? (
      <Content
        qywxs={qywxs}
        initialChoosed={initialChoosed}
        startTransfer={startTransfer}
        logout={logout}
        onFinish={onCancel}
      />
    ) : null}
  </EditModal>
}

function Content(props: {
  qywxs: QywxInfo[]
  initialChoosed: string
  startTransfer: (qywxs: QywxInfo[]) => void
  logout: (wxids: string[]) => void
  onFinish: () => void
}) {
  const { qywxs, initialChoosed, startTransfer, logout, onFinish } = props

  // 发现企业微信列表变空时，自动关闭对话框
  useEffect(() => {
    if (!qywxs.length) onFinish()
  }, [qywxs, onFinish])

  const [choosed, setChoosed] = useState(() => OrderedSet([initialChoosed]))
  const choosedRef = useRefValue(choosed)
  useEffect(() => {
    // 每当 qywxs 列表变化时，将已不存在的企业微信从 choosed 中移除
    const filtered = choosedRef.current.filter(wxid => qywxs.find(q => q.wxid === wxid))
    if (filtered.size !== choosedRef.current.size) setChoosed(filtered)
  }, [choosedRef, qywxs])

  const choose = useCallback(
    (wxid: string) => {
      const updated = choosed.has(wxid) ? choosed.delete(wxid) : choosed.add(wxid)
      setChoosed(updated)
    },
    [choosed],
  )
  const chooseAll = useCallback(() => {
    const updated = OrderedSet(choosed.size === qywxs.length ? [] : qywxs.map(q => q.wxid))
    setChoosed(updated)
  }, [choosed, qywxs])
  const allChoosed = choosed.size === qywxs.length
  const partialChoosed = !allChoosed && !!choosed.size

  function doStartTransfer() {
    startTransfer(choosed.toArray().map(wxid => qywxs.find(v => v.wxid === wxid)!))
    onFinish()
  }
  const doLogout = useCallback(() => {
    logout(choosed.toArray())
    onFinish()
  }, [choosed, logout, onFinish])

  return <>
    <header css={s.header}>
      <Checkbox checked={allChoosed} indeterminate={partialChoosed} onClick={chooseAll} />

      <Actionable strict>
        <Button disabled={!choosed.size} type="primary" size="small" onClick={doStartTransfer}>
          转交
        </Button>
      </Actionable>

      <Popconfirm onConfirm={doLogout} title={`确定要登出这${choosed.size}个企业微信吗？`}>
        <Button disabled={!choosed.size} type="primary" size="small">
          登出
        </Button>
      </Popconfirm>

      {choosed.size ? (
        <div className="count">
          已选中<span>{choosed.size}</span>个
        </div>
      ) : null}
    </header>

    <div css={s.main}>
      {qywxs.map(qywx => <div key={qywx.wxid} css={s.qywx} onClick={() => choose(qywx.wxid)}>
        <Checkbox checked={choosed.has(qywx.wxid)} />
        <img src={qywx.avatar || defaultAvatar} />
        <div className="info">
          <div>{qywx.friendlyName}</div>
          <div className="corpname">{qywx.corpname}</div>
        </div>
      </div>)}
    </div>
  </>
}

const s = {
  modal: css`
    .ant-checkbox-wrapper {
      margin-right: 12px;
    }
  `,
  header: css`
    align-items: center;
    background-color: #fafafa;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    padding: 12px 20px;
    button {
      margin-right: 12px;
      font-size: 13px;
    }
    .count {
      color: #aaa;
      flex: 1;
      font-size: 13px;
      text-align: right;
      span {
        padding: 0 2px;
      }
    }
  `,
  main: css`
    height: 500px;
    max-height: 50vw;
    overflow-y: auto;
    padding-bottom: 20px;
  `,
  qywx: css`
    align-items: center;
    cursor: pointer;
    display: flex;
    padding: 10px 20px;
    &:hover {
      background-color: #fafafa;
    }
    img {
      border-radius: 2px;
      height: 32px;
      margin-right: 10px;
      width: 32px;
    }
    .info {
      display: flex;
      flex-direction: column;
      flex: 1;
      font-size: 13px;
      justify-content: center;
      overflow: hidden;
      white-space: nowrap;
      & > * {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .corpname {
        color: #999;
        font-size: 12px;
      }
    }
  `,
}
